package jwtauth

import (
	"fmt"
	"strconv"
	"time"

	"gpt-api/framework/cache"
)

// 用户授权token存储接口
type Storer struct {
	store cache.Store
}

func NewStorer(store cache.Store) *Storer {
	return &Storer{store: store}
}

// 放入令牌，指定到期时间
func (s *Storer) Set(token, userID string, expiration time.Duration) error {
	return s.store.SetEx(s.wrapperKey(token), userID, expiration)
}

// 检查令牌是否存在
func (s *Storer) Check(token string) (uint64, error) {
	var val string
	key := s.wrapperKey(token)
	exist, err := s.store.Get(key, &val)
	if err != nil {
		return 0, err
	}
	if !exist {
		return 0, nil
	}
	s.store.Delete(key)

	return strconv.ParseUint(val, 10, 64)
}

// 关闭存储
func (s *Storer) Close() error {
	return s.store.Close()
}

func (s *Storer) wrapperKey(token string) string {
	return fmt.Sprintf("STR:USER:TOKEN:%s", token)
}
